package org.jeecg.modules.demo.Kingdee.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 附件上传工具类
 *
 * @author jeecg
 */
@Slf4j
@Component
public class AttachmentUploadUtil {

    private static K3CloudApi api;

    /**
     * 上传附件到金蝶系统
     *
     * @param fileName    文件名（包含后缀），如：发票号码.pdf 或 发票号码.jpg
     * @param formId      表单ID
     * @param billNo      单据编号
     * @param id          主键ID
     * @param inputStream 文件输入流
     * @throws Exception 上传过程中可能抛出的异常
     */
    public static void uploadAttachment(String fileName, String formId, String billNo, String id,
                                       InputStream inputStream) throws Exception {
        if (api == null) {
            throw new IllegalStateException("K3CloudApi未初始化");
        }

        File tempFile = File.createTempFile("download", ".tmp");
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            FileInputStream fileInputStream = new FileInputStream(tempFile);
            int blockSize = 1024 * 1024; // 分块大小：1M
            byte[] content = new byte[blockSize];
            String fileId = "";
            while (true) {
                int size = fileInputStream.read(content);
                if (size == 0) {
                    break;
                }
                boolean isLast = (size != blockSize);
                byte[] uploadBytes = Arrays.copyOf(content, size);
                Base64.Encoder encoder = Base64.getEncoder();
                String fileBase64String = encoder.encodeToString(uploadBytes);
                Map<String, Object> request = new HashMap<>();
                request.put("FileName", fileName);
                request.put("FormId", formId);
                request.put("IsLast", isLast);
                request.put("InterId", id);
                request.put("BillNo", billNo);
                request.put("AliasFileName", "test");
                request.put("FileId ", fileId);
                request.put("SendByte", fileBase64String);
                // 调用API的attachmentUpload方法
                String result = api.attachmentUpload(new Gson().toJson(request));
                log.info("附件上传结果：" + result);
                JsonObject resultObject = new JsonParser().parse(result).getAsJsonObject();
                JsonObject data = resultObject.get("Result").getAsJsonObject();
                // 第一个分块上传时，FileId是空，从第二个分块开始，FileId不能再为空
                fileId = data.get("FileId").getAsString();
                if (isLast) {
                    break;
                }
            }
        } finally {
            tempFile.delete();
            inputStream.close();
        }
    }

    /**
     * 初始化K3CloudApi实例
     */
    @PostConstruct
    public void initK3CloudApi() throws Exception {
        // 使用无参构造函数，让K3CloudApi自动从配置文件中读取配置
        api = new K3CloudApi();
    }
}